# coding=utf-8
# 代码文件：chapter2/ch2.8.py
import os
import threading
import time
import urllib.request

fileName = 'data/{0}股票历史交易数据.csv'


# 用来下载股票数据
def download(code):
    # 请求数据的URL网址
    url = 'http://quotes.money.163.com/service/chddata.html?code={0}&start={1}&end={2}&fields={3}'

    # 设置请求数据的字段
    fields = 'TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP'
    # 传递参数获得最终URL网址
    strURL = url.format(code, '20010827', '20210323', fields)
    print("请求的URL：", strURL)

    req = urllib.request.Request(strURL)

    with urllib.request.urlopen(req) as response:
        dataStr = response.read().decode(encoding='gbk', errors='ignore')
        print(dataStr)

        # 如果data文件夹不存在，则创建
        if not os.path.exists('data'):
            os.mkdir('data')

        with open(fileName.format(code), 'w+') as f:
            f.write(dataStr)
        print('下载文件成功')
        f.close()


# 线程体函数
def thread_body(code):
    print(code)
    # 当前线程对象
    t = threading.current_thread()
    print('线程{0}执行中...'.format(t.name))
    # 线程休眠
    time.sleep(5)
    download(code)
    print('线程{0}执行结束。'.format(t.name))


# 主函数
def main():
    # list = [{'0600028': '中国石化'},
    #         {'0601857': '中国石油'},
    #         {'0601939': '建设银行'},
    #         {'0601600': '中国铝业'}]

    list = ['0600028', '0601857', '0601939', '0601600']  # 要下载的股票代码的列表

    for item in list:
        # 创建线程对象
        thread = threading.Thread(target=thread_body,
                                  args=(item,))
        # 启动线程
        thread.start()


if __name__ == '__main__':
    main()
